package com.dstation.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dstation.domain.DynamicForPage;
import com.dstation.domain.DynamicInfo;
import com.dstation.domain.UserInfo;
import com.dstation.service.interf.IDynamicService;
import com.dstation.service.interf.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Eastward
 * @date 2022/5/3 - 15:45
 */
@Controller
@RequestMapping("/dynamic")
public class DynamicController {

    @Autowired
    private IDynamicService dynamicService;
    @Autowired
    private IUserService userService;

    /**
     * 进入动态主界面
     * */
    @RequestMapping("/homePage")
    public String queryAllDynamicInfo(ModelMap model,HttpSession session) {
        List<DynamicInfo> list = dynamicService.findAllDynamicInfo();
        List<DynamicForPage> nlist = new ArrayList<>();
        for (int i=0; i<list.size(); i++) {
            DynamicInfo dyn = list.get(i);
            DynamicForPage dynPage = new DynamicForPage();
            dynPage.setDynamicId(dyn.getDynamicId());
            dynPage.setUserId(dyn.getUserId());

            JSONObject json = JSONObject.parseObject(dyn.getDynamicContent());
            dynPage.setDynamicContent(json.getString("dynamicContent"));

            String str = json.getString("images");
            if (str == null ){
                dynPage.setImages(null);
            }else{
                String[] strlist = str.split("\\|");
                dynPage.setImages(new ArrayList<>(Arrays.asList(strlist)));
            }

            dynPage.setDynamicShareNum(dyn.getDynamicShareNum());
            dynPage.setDynamicViewNum(dyn.getDynamicViewNum());

            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(dyn.getCreateDate());
            dynPage.setCreateDate(date);

            UserInfo userInfo =  userService.findUserInfoByUserId(dyn.getUserId());
            dynPage.setCreatorIcon(userInfo.getUserIcon());
            dynPage.setCreatorName(userInfo.getUserName());

            long praiseNum = dynamicService.findPraiseNumByDynamicId(dyn.getDynamicId());
            dynPage.setLikedNum(praiseNum);

            long userId = ((UserInfo)session.getAttribute("userInfo")).getUserId();
            int isPraise = dynamicService.findUserIsPraiseByDynamicId(dyn.getDynamicId(),userId);
            dynPage.setIsPraise(isPraise);

            nlist.add(dynPage);
        }

        model.put("dynamicList",nlist);
        return "main/dynamicHomePage";
    }

    /**
     * 发布动态（纯文字）
     * @param dynamicContent
     * @param dynamicContent
     * @return
     */
    @PostMapping("/saveDynamicInfoOnlyContent")
    @ResponseBody
    public JSONObject saveDynamicInfoOnlyContent(@RequestPart("test") String dynamicContent,HttpSession session){
        JSONObject jsonObject = new JSONObject();
        DynamicInfo dynamic = new DynamicInfo();
        dynamic.setDynamicContent(dynamicContent);
        dynamic.setUserId(((UserInfo)session.getAttribute("userInfo")).getUserId());
        dynamic.setDynamicShareNum(0);
        dynamic.setDynamicViewNum(0);
        dynamic.setDynamicViewNum(0);
        dynamic.setIsPass(false);
        dynamic.setCreateDate(new Timestamp(System.currentTimeMillis()));
        boolean saveRes = dynamicService.addDynamicInfo(dynamic);
        if (saveRes){
            jsonObject.put("res","success");
        }else{
            jsonObject.put("res","error");
        }
        return jsonObject;
    }

    /**
     * 发布动态（文配图）
     * @param multipartFile
     * @param dynamicContent
     * @return
     */
    @PostMapping("/saveDynamicInfo")
    @ResponseBody
    public JSONObject saveDynamicInfo(@RequestParam("meFile") MultipartFile[] multipartFile, @RequestPart("test") String dynamicContent,HttpSession session){
        JSONObject jsonObject = new JSONObject();
        JSONObject dynJson = JSONObject.parseObject(dynamicContent);

        String images = "";
        for (int i=0; i < multipartFile.length; i++){
            MultipartFile file = multipartFile[i];
            uploadImage(file);
            images += file.getOriginalFilename() + "|";
        }
        dynJson.put("images",images);

        String str = JSON.toJSONString(dynJson);
        DynamicInfo dynamic = new DynamicInfo();
        dynamic.setDynamicContent(str);
        dynamic.setUserId(((UserInfo)session.getAttribute("userInfo")).getUserId());
        dynamic.setDynamicShareNum(0);
        dynamic.setDynamicViewNum(0);
        dynamic.setDynamicViewNum(0);
        dynamic.setIsPass(false);
        dynamic.setCreateDate(new Timestamp(System.currentTimeMillis()));
        boolean saveRes = dynamicService.addDynamicInfo(dynamic);
        if (saveRes){
            jsonObject.put("res","success");
        }else{
            jsonObject.put("res","error");
        }
        return jsonObject;
    }

    /**
     * 查看动态
     */
    @GetMapping("/findDynamicInfo")
    public String findDynamicInfo(@RequestParam("dynamicId")long dynamicId, HttpSession session, ModelMap modelMap) {
        DynamicInfo dyn = dynamicService.queryDynamicInfoByDynamicId(dynamicId);
        DynamicForPage dynPage = new DynamicForPage();
        dynPage.setDynamicId(dyn.getDynamicId());
        dynPage.setUserId(dyn.getUserId());

        JSONObject json = JSONObject.parseObject(dyn.getDynamicContent());
        dynPage.setDynamicContent(json.getString("dynamicContent"));

        String str = json.getString("images");
        if (str == null ){
            dynPage.setImages(null);
        }else{
            String[] strlist = str.split("\\|");
            dynPage.setImages(new ArrayList<>(Arrays.asList(strlist)));
        }

        dynPage.setDynamicShareNum(dyn.getDynamicShareNum());
        dynPage.setDynamicViewNum(dyn.getDynamicViewNum());

        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(dyn.getCreateDate());
        dynPage.setCreateDate(date);

        UserInfo userInfo =  userService.findUserInfoByUserId(dyn.getUserId());
        dynPage.setCreatorIcon(userInfo.getUserIcon());
        dynPage.setCreatorName(userInfo.getUserName());

        long praiseNum = dynamicService.findPraiseNumByDynamicId(dyn.getDynamicId());
        dynPage.setLikedNum(praiseNum);

        long userId = ((UserInfo)session.getAttribute("userInfo")).getUserId();
        int isPraise = dynamicService.findUserIsPraiseByDynamicId(dyn.getDynamicId(),userId);
        dynPage.setIsPraise(isPraise);

        modelMap.put("dynamic",dynPage);
        return "main/dynamicCheckPage";
    }

    /**
     * 删除动态
     * @param dynamicId
     * @return
     */
    @PostMapping("/removeDynamicInfo")
    @ResponseBody
    public JSONObject removeDynamicInfo(@RequestParam("dynamicId")long dynamicId){
        JSONObject json = new JSONObject();
        boolean removeRes = dynamicService.dropDynamicInfo(dynamicId);
        if (removeRes){
            json.put("removeRes","success");
        }else{
            json.put("removeRes","error");
        }
        return json;
    }

    /**
     * 动态点赞
     * @param dynamicId
     * @return
     */
    @RequestMapping(value = "/praiseDynamic")
    @ResponseBody
    public JSONObject praiseDynamic(@RequestParam("dynamicId")long dynamicId, HttpSession session) {
        // 1. 首先查询 用户点赞表 得到现在的 点赞状态
        int dynamicLikedInfo = dynamicService.findUserIsPraiseByDynamicId(dynamicId,
                ((UserInfo)session.getAttribute("userInfo")).getUserId());
        JSONObject jsonObject = new JSONObject();
        //2. 若现在为null,表示还没有点赞信息
        if(dynamicLikedInfo == 0) {  //插入一条点赞信息
            boolean saveRes = dynamicService.addUserPraiseDynamicInfo(dynamicId, ((UserInfo)session.getAttribute("userInfo")).getUserId(), new Timestamp(System.currentTimeMillis()));
            jsonObject.put("res", "add");   //点赞
        } else {    //删除点赞消息
            boolean removeRes = dynamicService.dropUserPraiseDynamicInfo(dynamicId, ((UserInfo)session.getAttribute("userInfo")).getUserId());
            jsonObject.put("res", "sub");   //点赞
        }
        //3. 查询现在的点赞数量，更新前台界面
        long praiseNum = dynamicService.findPraiseNumByDynamicId(dynamicId);
        jsonObject.put("praiseNum", praiseNum);
        return jsonObject;
    }

    /**
     * 编辑动态页面
     */
    @RequestMapping(value = "/updateDynamicInfoPage")
    public String updateDynamicInfoPage(@RequestParam("dynamicId")long dynamicId, HttpSession session, ModelMap modelMap){
        DynamicInfo dyn = dynamicService.queryDynamicInfoByDynamicId(dynamicId);
        DynamicForPage dynPage = new DynamicForPage();
        dynPage.setDynamicId(dyn.getDynamicId());
        dynPage.setUserId(dyn.getUserId());

        JSONObject json = JSONObject.parseObject(dyn.getDynamicContent());
        dynPage.setDynamicContent(json.getString("dynamicContent"));

        String str = json.getString("images");
        if (str == null ){
            dynPage.setImages(null);
        }else{
            String[] strlist = str.split("\\|");
            dynPage.setImages(new ArrayList<>(Arrays.asList(strlist)));
        }

        dynPage.setDynamicShareNum(dyn.getDynamicShareNum());
        dynPage.setDynamicViewNum(dyn.getDynamicViewNum());

        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(dyn.getCreateDate());
        dynPage.setCreateDate(date);

        UserInfo userInfo =  userService.findUserInfoByUserId(dyn.getUserId());
        dynPage.setCreatorIcon(userInfo.getUserIcon());
        dynPage.setCreatorName(userInfo.getUserName());

        long praiseNum = dynamicService.findPraiseNumByDynamicId(dyn.getDynamicId());
        dynPage.setLikedNum(praiseNum);

        long userId = ((UserInfo)session.getAttribute("userInfo")).getUserId();
        int isPraise = dynamicService.findUserIsPraiseByDynamicId(dyn.getDynamicId(),userId);
        dynPage.setIsPraise(isPraise);

        modelMap.put("dynamic",dynPage);
        return "main/updateDynamicInfoPage";
    }

    /**
     * 修改动态（文配图）
     * @param multipartFile
     * @param dynamicContent
     * @return
     */
    @PostMapping("/modifyDynamicInfo")
    @ResponseBody
    public JSONObject modifyDynamicInfo(@RequestParam("meFile") MultipartFile[] multipartFile,
                                        @RequestParam("dynamicContent") String dynamicContent,
                                        @RequestParam("dynamicId")long dynamicId){
        JSONObject jsonObject = new JSONObject();
        DynamicInfo dynamic = new DynamicInfo();
        JSONObject dynJson = JSONObject.parseObject(dynamicContent);

        String images = dynJson.getString("images");
        String files = "";
        if (images != null && images != ""){
            String[] strlist = images.split(",");
            String dynImages = String.join("\\|",strlist);;
            String str2 = dynImages.replace("\\", "");
            String str3 = str2.replace("\"", "");
            files = str3.substring(1,str3.length()-1) + "|";
        }
        for (int i=0; i < multipartFile.length; i++){
            MultipartFile file = multipartFile[i];
            uploadImage(file);
            files += file.getOriginalFilename() + "|";
        }
        dynJson.put("images",files);

        String str = JSON.toJSONString(dynJson);

        dynamic.setDynamicContent(str);
        dynamic.setIsPass(false);
        dynamic.setDynamicId(dynamicId);
        dynamic.setCreateDate(new Timestamp(System.currentTimeMillis()));
        boolean saveRes = dynamicService.alterDynamicInfo(dynamic);
        if (saveRes){
            jsonObject.put("res","success");
        }else{
            jsonObject.put("res","error");
        }
        return jsonObject;
    }

    /**
     * 动态修改
     * @param dynamicContent
     * @return
     */
    @PostMapping("/modifyDynamicInfoOnlyContent")
    @ResponseBody
    public JSONObject modifyDynamicInfoOnlyContent(@RequestParam("dynamicContent") String dynamicContent,
                                                   @RequestParam("dynamicId")long dynamicId){
        JSONObject jsonObject = new JSONObject();
        DynamicInfo dynamic = new DynamicInfo();
        JSONObject dynJson = JSONObject.parseObject(dynamicContent);
        String images = dynJson.getString("images");
        if (images == null || images == ""){
            dynamic.setDynamicContent(dynamicContent);
        }else{
            String[] strlist = images.split(",");
            String dynImages = String.join("\\|",strlist);;
            String str2 = dynImages.replace("\\", "");
            String str3 = str2.replace("\"", "");
            String str4 = str3.substring(1,str3.length()-1);
            dynJson.put("images",str4);
            String str = JSON.toJSONString(dynJson);
            dynamic.setDynamicContent(str);
        }
        dynamic.setDynamicId(dynamicId);
        dynamic.setIsPass(false);
        dynamic.setCreateDate(new Timestamp(System.currentTimeMillis()));
        boolean modifyResult = dynamicService.alterDynamicInfo(dynamic);
        if (modifyResult){
            jsonObject.put("res","success");
        }else{
            jsonObject.put("res","error");
        }
        return jsonObject;
    }

    private void uploadImage(@RequestBody MultipartFile file) {
        //判断文件是否存在
        if (file == null) {
            throw new RuntimeException("文件不存在");
        }
        //获取文件的完整名称
        String originalFilename = file.getOriginalFilename();
        String filePath = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\images\\dynImages\\";
        File dest = new File(filePath + originalFilename);
        try {
            file.transferTo(dest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
